import os
import sys

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox

from config import DATA_PATH


class ActivationDialog(QDialog):
    def __init__(self, host_name_md5):
        super(ActivationDialog, self).__init__()

        self.host_name_md5 = host_name_md5

        # 设置窗口标题
        self.setWindowTitle("Software Activation")

        # 设置窗口大小
        self.resize(400, 200)

        # 创建布局
        layout = QVBoxLayout()

        # 添加提示标签
        prompt_label = QLabel("Please enter the activation key:")
        layout.addWidget(prompt_label)

        # 添加输入框
        self.key_input = QLineEdit()
        self.key_input.setFixedSize(400, 30)
        self.key_input.setPlaceholderText("Please enter the activation key")
        layout.addWidget(self.key_input)

        # 添加激活按钮
        activate_button = QPushButton("Activation")
        activate_button.clicked.connect(self.activate_software)
        activate_button.setFixedSize(400, 30)
        layout.addWidget(activate_button)

        # 添加版权信息标签
        copyright_label = QLabel(
            "Copyright © 2024 JCI APAC Data Team\nJerry Zang(jzangc@.jci.com)")
        copyright_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(copyright_label)

        # 添加结果标签
        self.result_label = QLabel("")
        self.result_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.result_label)

        # 设置布局
        self.setLayout(layout)

    def activate_software(self):
        # 获取输入的密钥
        key = self.key_input.text().strip().lower()
        # 检查密钥是否有效
        if key == self.host_name_md5:  # 示例密钥，实际应用中应使用更复杂的验证逻辑
            self.result_label.setText("Activation Successful!")
            self.result_label.setStyleSheet("color: green;")
            # 写入激活状态到文件
            with open(os.path.join(DATA_PATH, "refer.txt"), "w") as f:
                f.write(key)
            self.accept()
        else:
            self.result_label.setText("The activation failed, please check whether the key is correct.")
            self.result_label.setStyleSheet("color: red;")

    def closeEvent(self, event):
        # 确认用户是否真的要关闭窗口
        reply = QMessageBox.question(self, 'Exit', 'Do you confirm the exit？',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            sys.exit()  # 接受关闭事件，退出应用程序
        else:
            event.ignore()  #